const validate = require("validate.js");
const blogtypeDao = require("../dao/blogtypeDao");
const blogDao = require("../dao/blogDao");

exports.addBlogtype = async (info) => {
    const res = validate.validate(info, {
        name: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        order: {
            presence: {
                allowEmpty: false
            },
            type: "integer"
        }
    });
    if (!res) {
        info.articleCount = 0;
        return await blogtypeDao.addBlogtype(info);
    } else {
        console.log(res);
        throw new ValidationError("数据验证失败");
    }
}

exports.getBlogtypes = async () => {
    const res = await blogtypeDao.getBlogtypes();
    res.sort((a, b)=>{
        return a.order - b.order;
    });
    return res;
}

exports.getBlogtypeById = async (id) => {
    return await blogtypeDao.getBlogtypeById(id);
}

exports.updateBlogtype = async (id, newInfo) => {
    return await blogtypeDao.updateBlogtype(id, newInfo);
}

exports.deleteBlogtype = async (id) => {
    await blogtypeDao.deleteBlogtype(id);
    return await blogDao.getBlogCountByBlogtype(id);
}
